package com.ctshk.rpc.system.service.impl;

import cn.hutool.core.lang.tree.Tree;
import cn.hutool.core.lang.tree.TreeNodeConfig;
import cn.hutool.core.lang.tree.TreeUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.*;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ctshk.common.constant.ElasticSearchConstant;
import com.ctshk.common.dto.Result;
import com.ctshk.common.elasticsearch.config.ElasticSearchConfiguration;
import com.ctshk.common.enums.IsDeletedCode;
import com.ctshk.common.enums.SysAreaLevel;
import com.ctshk.common.enums.SystemError;
import com.ctshk.common.model.PageResponse;
import com.ctshk.common.utils.EntityUtil;
import com.ctshk.rpc.system.dto.*;
import com.ctshk.rpc.system.entity.SysArea;
import com.ctshk.rpc.system.entity.SysAreaDTO;
import com.ctshk.rpc.system.entity.SysAreaTest;
import com.ctshk.rpc.system.mapper.SysAreaElasticSearchMapper;
import com.ctshk.rpc.system.mapper.SysAreaMapper;
import com.ctshk.rpc.system.req.*;
import com.ctshk.rpc.system.service.ISysAreaService;
import com.github.houbb.opencc4j.util.ZhConverterUtil;
import org.apache.dubbo.config.annotation.DubboService;
import org.elasticsearch.action.get.GetRequest;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.action.update.UpdateRequest;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.client.indices.GetIndexRequest;
import org.elasticsearch.common.xcontent.XContentType;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.index.query.TermsQueryBuilder;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.springframework.beans.factory.annotation.Autowired;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.stream.Collectors;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author 谢诗宏
 * @since 2021-01-11
 */
@DubboService
public class SysAreaServiceImpl extends ServiceImpl<SysAreaMapper, SysArea> implements ISysAreaService {

    public static final String CN = "4RS";
    public static final String TW = "CP4";
    public static final String XG = "824";
    public static final String AM = "7ID";

    // 国家地区定时任务 扫描起始时间
    private static LocalDateTime lastModifiedTime;

    @Resource
    private SysAreaTestServiceImpl sysAreaTestService;

    @Autowired
    private SysAreaElasticSearchMapper sysAreaElasticSearchMapper;

    @Autowired
    private RestHighLevelClient restHighLevelClient;

    @Override
    public List<AreaDTO> queryListEs(AreaQueryReq areaQueryReq) {
        List<AreaDTO> list = new ArrayList<>();
        SearchSourceBuilder ssb = new SearchSourceBuilder();
        BoolQueryBuilder bqb = QueryBuilders.boolQuery();
        if (!org.apache.commons.lang.StringUtils.isEmpty(areaQueryReq.getName())) {
            bqb.must(QueryBuilders.boolQuery()
                    .should(QueryBuilders.matchPhraseQuery("countrySimple", areaQueryReq.getName()))
                    .should(QueryBuilders.matchPhraseQuery("provinceSimple", areaQueryReq.getName()))
                    .should(QueryBuilders.matchPhraseQuery("citySimple", areaQueryReq.getName()))
                    .should(QueryBuilders.matchPhraseQuery("areaSimple", areaQueryReq.getName()))
                    .should(QueryBuilders.matchPhraseQuery("countryPinyin", areaQueryReq.getName()))
                    .should(QueryBuilders.matchPhraseQuery("provincePinyin", areaQueryReq.getName()))
                    .should(QueryBuilders.matchPhraseQuery("cityPinyin", areaQueryReq.getName()))
                    .should(QueryBuilders.matchPhraseQuery("areaPinyin", areaQueryReq.getName()))
                    .should(QueryBuilders.matchPhraseQuery("countryTraditional", areaQueryReq.getName()))
                    .should(QueryBuilders.matchPhraseQuery("provinceTraditional", areaQueryReq.getName()))
                    .should(QueryBuilders.matchPhraseQuery("cityTraditional", areaQueryReq.getName()))
                    .should(QueryBuilders.matchPhraseQuery("areaTraditional", areaQueryReq.getName()))
            );
        }
        bqb.mustNot(QueryBuilders.termQuery("level", SysAreaLevel.FOUR.getCode()));
        ssb.query(bqb);
        ssb.size(ObjectUtils.isEmpty(areaQueryReq.getSize()) ? ElasticSearchConstant.PAGE_SIZE : areaQueryReq.getSize());
        SearchRequest sr = new SearchRequest(ElasticSearchConstant.SYSTEM_AREA).source(ssb);
        try {
            SearchResponse search = restHighLevelClient.search(sr, ElasticSearchConfiguration.COMMON_OPTIONS);
            // 检索到的命中记录
            SearchHits hits = search.getHits();
            // 提取检索到的记录
            SearchHit[] searchHits = hits.getHits();
            if (searchHits != null && searchHits.length > 0) {
                for (SearchHit sh : searchHits) {
                    String source = sh.getSourceAsString();
                    // 将命中记录反序列化成目的地对象
                    AreaDTO area = JSON.parseObject(source, AreaDTO.class);
                    list.add(area);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return list;
    }

    @Override
    public List<AreaDTO> queryListEsWhere(AreaQueryWhereReq req) {
        List<AreaDTO> list = new ArrayList<>();
        SearchSourceBuilder ssb = new SearchSourceBuilder();
        BoolQueryBuilder bqb = QueryBuilders.boolQuery();
        if (!org.apache.commons.lang.StringUtils.isEmpty(req.getName())) {
            bqb.must(QueryBuilders.boolQuery()
                    .should(QueryBuilders.matchPhraseQuery("countrySimple", req.getName()))
                    .should(QueryBuilders.matchPhraseQuery("provinceSimple", req.getName()))
                    .should(QueryBuilders.matchPhraseQuery("citySimple", req.getName()))
                    .should(QueryBuilders.matchPhraseQuery("areaSimple", req.getName()))
                    .should(QueryBuilders.matchPhraseQuery("countryPinyin", req.getName()))
                    .should(QueryBuilders.matchPhraseQuery("provincePinyin", req.getName()))
                    .should(QueryBuilders.matchPhraseQuery("cityPinyin", req.getName()))
                    .should(QueryBuilders.matchPhraseQuery("areaPinyin", req.getName()))
                    .should(QueryBuilders.matchPhraseQuery("countryTraditional", req.getName()))
                    .should(QueryBuilders.matchPhraseQuery("provinceTraditional", req.getName()))
                    .should(QueryBuilders.matchPhraseQuery("cityTraditional", req.getName()))
                    .should(QueryBuilders.matchPhraseQuery("areaTraditional", req.getName()))
            );
        }
        if (req.getType() != null) {
            switch (req.getType()) {
                case 1: //国内
                    bqb.must(QueryBuilders.boolQuery()
                            .should(QueryBuilders.matchPhraseQuery("countryCode", CN))
                            .should(QueryBuilders.matchPhraseQuery("countryCode", TW))
                            .should(QueryBuilders.matchPhraseQuery("countryCode", XG))
                            .should(QueryBuilders.matchPhraseQuery("countryCode", AM))
                    );
                    break;
                case 2: //国外
                    bqb.mustNot(QueryBuilders.boolQuery()
                            .should(QueryBuilders.matchPhraseQuery("countryCode", CN))
                            .should(QueryBuilders.matchPhraseQuery("countryCode", TW))
                            .should(QueryBuilders.matchPhraseQuery("countryCode", XG))
                            .should(QueryBuilders.matchPhraseQuery("countryCode", AM))
                    );
                    break;
            }
        }
        if (req.getLevels() != null && req.getLevels().size() > 0) {
            BoolQueryBuilder bqbq = QueryBuilders.boolQuery();
            req.getLevels().forEach(e -> {
                bqbq.should(QueryBuilders.termQuery("level", e));
            });
            bqb.must(bqbq);
        } else if (req.getLevel() != null) {
            bqb.must(QueryBuilders.termQuery("level", req.getLevel()));
        }
        ssb.size(req.getSize());
        ssb.query(bqb);
        SearchRequest sr = new SearchRequest(ElasticSearchConstant.SYSTEM_AREA).source(ssb);
        try {
            SearchResponse search = restHighLevelClient.search(sr, ElasticSearchConfiguration.COMMON_OPTIONS);
            // 检索到的命中记录
            SearchHits hits = search.getHits();
            // 提取检索到的记录
            SearchHit[] searchHits = hits.getHits();
            if (searchHits != null && searchHits.length > 0) {
                for (SearchHit sh : searchHits) {
                    String source = sh.getSourceAsString();
                    // 将命中记录反序列化成目的地对象
                    AreaDTO area = JSON.parseObject(source, AreaDTO.class);
                    if ((req.isFlagTwo() && area.getLevel() == SysAreaLevel.TWO.getCode()) || (req.isFlagOne() && area.getLevel() == SysAreaLevel.ONE.getCode())) {
                        if (XG.equals(area.getCountryCode()) || AM.equals(area.getCountryCode()) || TW.equals(area.getCountryCode())) {
                            list.add(area);
                        }
                    } else if (req.isFlagOneAndTwo() && (area.getLevel() == SysAreaLevel.ONE.getCode() || area.getLevel() == SysAreaLevel.TWO.getCode())) {
                        if (area.getLevel() == SysAreaLevel.TWO.getCode()) {
                            if (!XG.equals(area.getCountryCode()) && !AM.equals(area.getCountryCode()) && !TW.equals(area.getCountryCode())) {
                                list.add(area);
                            }
                        } else if (area.getLevel() == SysAreaLevel.ONE.getCode()) {
                            if (XG.equals(area.getCountryCode()) || AM.equals(area.getCountryCode()) || TW.equals(area.getCountryCode())) {
                                list.add(area);
                            }
                        }
                    } else {
                        list.add(area);
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return list;
    }

    @Override
    public List<AreaDTO> queryListEsByLevel(AreaQueryLevelReq req) {
        List<AreaDTO> list = new ArrayList<>();
        SearchSourceBuilder ssb = new SearchSourceBuilder();
        BoolQueryBuilder bqb = QueryBuilders.boolQuery();
        if (req.getType() != null) {
            bqb.must(QueryBuilders.termQuery("level", req.getType()));
            if (StringUtils.isNotBlank(req.getPatenCode())) {
                switch (req.getType()) {
                    case 2:
                        bqb.must(QueryBuilders.matchPhraseQuery("countryCode", req.getPatenCode()));
                        break;
                    case 3:
                        bqb.must(QueryBuilders.matchPhraseQuery("provinceCode", req.getPatenCode()));
                        break;
                    case 4:
                        bqb.must(QueryBuilders.matchPhraseQuery("cityCode", req.getPatenCode()));
                        break;
                }
            }
            if (req.getLevel() != null) {
                switch (req.getLevel()) {
                    case 1: //国内
                        bqb.must(QueryBuilders.boolQuery()
                                .should(QueryBuilders.matchPhraseQuery("countryCode", CN))
                                .should(QueryBuilders.matchPhraseQuery("countryCode", TW))
                                .should(QueryBuilders.matchPhraseQuery("countryCode", XG))
                                .should(QueryBuilders.matchPhraseQuery("countryCode", AM))
                        );
                        break;
                    case 2: //国外
                        bqb.mustNot(QueryBuilders.boolQuery()
                                .should(QueryBuilders.matchPhraseQuery("countryCode", CN))
                                .should(QueryBuilders.matchPhraseQuery("countryCode", TW))
                                .should(QueryBuilders.matchPhraseQuery("countryCode", XG))
                                .should(QueryBuilders.matchPhraseQuery("countryCode", AM))
                        );
                        break;
                }
            }
        }
        ssb.size(100);//每一层不会超过100吧
        ssb.query(bqb);
        SearchRequest sr = new SearchRequest(ElasticSearchConstant.SYSTEM_AREA).source(ssb);
        try {
            SearchResponse search = restHighLevelClient.search(sr, ElasticSearchConfiguration.COMMON_OPTIONS);
            // 检索到的命中记录
            SearchHits hits = search.getHits();
            // 提取检索到的记录
            SearchHit[] searchHits = hits.getHits();
            if (searchHits != null && searchHits.length > 0) {
                for (SearchHit sh : searchHits) {
                    String source = sh.getSourceAsString();
                    // 将命中记录反序列化成目的地对象
                    AreaDTO area = JSON.parseObject(source, AreaDTO.class);
                    list.add(area);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return list;
    }

    @Override
    public JSONArray queryListEsByLevelTwo(AreaILevelReq req) {
        JSONArray resultJson = new JSONArray();
        List<AreaDTO> listOne = new ArrayList<>();
        List<AreaDTO> listTwo = new ArrayList<>();
        ArrayList<AreaDTO> listThree = new ArrayList<>();
        ArrayList<AreaDTO> listFour = new ArrayList<>();
        SearchSourceBuilder ssb = new SearchSourceBuilder();
        BoolQueryBuilder bqb = QueryBuilders.boolQuery();
        if (req.getType() != null) {
            switch (req.getType()) {
                case 1: //国内
                    bqb.must(QueryBuilders.matchPhraseQuery("countryCode", CN));
                    break;
                case 2: //国外
                    bqb.mustNot(QueryBuilders.boolQuery()
                            .should(QueryBuilders.matchPhraseQuery("countryCode", CN))
                            .should(QueryBuilders.matchPhraseQuery("countryCode", TW))
                            .should(QueryBuilders.matchPhraseQuery("countryCode", XG))
                            .should(QueryBuilders.matchPhraseQuery("countryCode", AM))
                    );
                    break;
            }
        }
        if (req.getType() == 1 && req.isFlage()) {
            bqb.must(QueryBuilders.boolQuery()
                    .should(QueryBuilders.termQuery("level", SysAreaLevel.TWO.getCode()))
                    .should(QueryBuilders.termQuery("level", SysAreaLevel.THREE.getCode()))
                    .should(QueryBuilders.termQuery("level", SysAreaLevel.FOUR.getCode()))
            );
        } else {
            if (req.getType() == 1) {
                bqb.must(QueryBuilders.boolQuery()
                        .should(QueryBuilders.termQuery("level", SysAreaLevel.TWO.getCode()))
                        .should(QueryBuilders.termQuery("level", SysAreaLevel.THREE.getCode()))
                );
            } else {
                if (req.isOutFlage()) {
                    bqb.must(QueryBuilders.boolQuery()
                            .should(QueryBuilders.termQuery("level", SysAreaLevel.ONE.getCode()))
                            .should(QueryBuilders.termQuery("level", SysAreaLevel.TWO.getCode()))
                    );
                } else {
                    bqb.must(QueryBuilders.boolQuery()
                            .should(QueryBuilders.termQuery("level", SysAreaLevel.TWO.getCode()))
                            .should(QueryBuilders.termQuery("level", SysAreaLevel.THREE.getCode()))
                    );
                }
            }
        }
        ssb.size(10000);
        ssb.query(bqb);
        SearchRequest sr = new SearchRequest(ElasticSearchConstant.SYSTEM_AREA).source(ssb);
        try {
            SearchResponse search = restHighLevelClient.search(sr, ElasticSearchConfiguration.COMMON_OPTIONS);
            // 检索到的命中记录
            SearchHits hits = search.getHits();
            // 提取检索到的记录
            SearchHit[] searchHits = hits.getHits();
            if (searchHits != null && searchHits.length > 0) {
                for (SearchHit sh : searchHits) {
                    String source = sh.getSourceAsString();
                    // 将命中记录反序列化成目的地对象
                    AreaDTO area = JSON.parseObject(source, AreaDTO.class);
                    if (area.getLevel() == SysAreaLevel.ONE.getCode()) {
                        listOne.add(area);
                    } else if (area.getLevel() == SysAreaLevel.TWO.getCode()) {
                        listTwo.add(area);
                    } else if (area.getLevel() == SysAreaLevel.THREE.getCode()) {
                        listThree.add(area);
                    } else {
                        listFour.add(area);
                    }
                }
                if (req.getType() == 2 && req.isOutFlage()) {
                    listOne.forEach(one -> {
                        JSONObject json = new JSONObject();
                        json.put("key", one.getId());
                        json.put("title", one.getCountryTraditional());
                        JSONArray children = new JSONArray();
                        listTwo.forEach(two -> {
                            if (one.getCountryTraditional().equals(two.getCountryTraditional())) {
                                JSONObject jsonCity = new JSONObject();
                                jsonCity.put("key", two.getId());
                                jsonCity.put("title", two.getProvinceTraditional());
                                jsonCity.put("children", null);//第二级后面没有子级了
                                children.add(jsonCity);
                            }
                        });
                        json.put("children", children);
                        resultJson.add(json);
                    });
                } else {
                    listTwo.forEach(two -> {
                        JSONObject json = new JSONObject();
                        json.put("key", two.getId());
                        json.put("title", two.getProvinceTraditional());
                        JSONArray children = new JSONArray();
                        listThree.forEach(three -> {
                            //第三级的父级省份code等于第二级的省份code就是其子级
                            if (two.getProvinceCode().equals(three.getProvinceCode())) {
                                JSONObject jsonCity = new JSONObject();
                                jsonCity.put("key", three.getId());
                                jsonCity.put("title", three.getCityTraditional());
                                if (req.getType() == 1 && req.isFlage()) {
                                    //需要4级
                                    JSONArray childrenFour = new JSONArray();
                                    listFour.forEach(four -> {
                                        if (three.getCityCode().equals(four.getCityCode())) {
                                            JSONObject jsonArea = new JSONObject();
                                            jsonArea.put("key", four.getId());
                                            jsonArea.put("title", four.getAreaTraditional());
                                            jsonArea.put("children", null);
                                            childrenFour.add(jsonArea);
                                        }
                                    });
                                    jsonCity.put("children", childrenFour);
                                } else {
                                    jsonCity.put("children", null);//第三级后面没有子级了
                                }
                                children.add(jsonCity);
                            }
                        });
                        json.put("children", children);
                        resultJson.add(json);
                    });
                }
                if (req.getType() == 1) {
                    JSONObject json = new JSONObject();
                    json.put("key", "0");
                    json.put("title", "港澳台");
                    JSONArray children = new JSONArray();
                    AreaQueryLevelReq aqlr = new AreaQueryLevelReq();
                    aqlr.setType(SysAreaLevel.ONE.getCode());
                    aqlr.setLevel(1);
                    List<AreaDTO> result2 = queryListEsByLevel(aqlr);
                    ArrayList<AreaDTO> fours = new ArrayList<>();
                    if (req.isFlage()) {
                        aqlr.setType(SysAreaLevel.TWO.getCode());
                        aqlr.setPatenCode(XG);
                        List<AreaDTO> xgs = queryListEsByLevel(aqlr);
                        aqlr.setPatenCode(AM);
                        List<AreaDTO> ams = queryListEsByLevel(aqlr);
                        aqlr.setPatenCode(TW);
                        List<AreaDTO> tws = queryListEsByLevel(aqlr);
                        fours.addAll(xgs);
                        fours.addAll(ams);
                        fours.addAll(tws);
                    }
                    result2.forEach(three -> {
                        if (!CN.equals(three.getCountryCode())) {
                            JSONObject gat = new JSONObject();
                            gat.put("key", three.getId());
                            gat.put("title", three.getCountryTraditional());
                            if (req.isFlage()) {
                                JSONArray childrenFour = new JSONArray();
                                fours.forEach(four -> {
                                    if (three.getCountryCode().equals(four.getCountryCode())) {
                                        JSONObject gatf = new JSONObject();
                                        gatf.put("key", four.getId());
                                        gatf.put("title", four.getProvinceTraditional());
                                        gatf.put("children", null);
                                        childrenFour.add(gatf);
                                    }
                                });
                                gat.put("children", childrenFour);
                            } else {
                                gat.put("children", null);
                            }
                            children.add(gat);
                        }
                    });
                    json.put("children", children);
                    resultJson.add(json);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return resultJson;
    }

    @Override
    public AreaDTO queryByEsId(Long id) {
        AreaDTO areaDTO = new AreaDTO();
        SearchSourceBuilder ssb = new SearchSourceBuilder();
        BoolQueryBuilder bqb = QueryBuilders.boolQuery();
        bqb.must(QueryBuilders.termQuery("id", id));
        ssb.size(1);
        ssb.query(bqb);
        SearchRequest sr = new SearchRequest(ElasticSearchConstant.SYSTEM_AREA).source(ssb);
        try {
            SearchResponse search = restHighLevelClient.search(sr, ElasticSearchConfiguration.COMMON_OPTIONS);
            // 检索到的命中记录
            SearchHits hits = search.getHits();
            // 提取检索到的记录
            SearchHit[] searchHits = hits.getHits();
            if (searchHits != null && searchHits.length > 0) {
                String source = searchHits[0].getSourceAsString();
                return JSON.parseObject(source, AreaDTO.class);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return areaDTO;
    }

    @Override
    public List<AreaDTO> queryAreaDTOListByEsIds(List<Long> ids) {
        List<AreaDTO> areaDTOList = new ArrayList<>();
        SearchSourceBuilder ssb = new SearchSourceBuilder();
        TermsQueryBuilder qb = QueryBuilders.termsQuery("id", ids);
        ssb.size(2);
        ssb.query(qb);
        SearchRequest sr = new SearchRequest(ElasticSearchConstant.SYSTEM_AREA).source(ssb);
        try {
            SearchResponse search = restHighLevelClient.search(sr, ElasticSearchConfiguration.COMMON_OPTIONS);
            // 检索到的命中记录
            SearchHits hits = search.getHits();
            // 提取检索到的记录
            SearchHit[] searchHits = hits.getHits();
            if (searchHits != null && searchHits.length > 0) {
                for (SearchHit searchHit : searchHits) {
                    String source = searchHit.getSourceAsString();
                    AreaDTO areaDTO = JSON.parseObject(source, AreaDTO.class);
                    areaDTOList.add(areaDTO);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return areaDTOList;
    }

    @Override
    public List<AreaTreeListDTO> queryByEsIds(List<Long> ids) {
        List<AreaTreeListDTO> areaTreeList = new ArrayList<>();
        SearchSourceBuilder ssb = new SearchSourceBuilder();
        TermsQueryBuilder qb = QueryBuilders.termsQuery("id", ids);
        ssb.size(4);
        ssb.query(qb);
        SearchRequest sr = new SearchRequest(ElasticSearchConstant.SYSTEM_AREA).source(ssb);
        try {
            SearchResponse search = restHighLevelClient.search(sr, ElasticSearchConfiguration.COMMON_OPTIONS);
            // 检索到的命中记录
            SearchHits hits = search.getHits();
            // 提取检索到的记录
            SearchHit[] searchHits = hits.getHits();
            if (searchHits != null && searchHits.length > 0) {
                for (SearchHit searchHit : searchHits) {
                    String source = searchHit.getSourceAsString();
                    AreaDTO areaDTO = JSON.parseObject(source, AreaDTO.class);
                    AreaTreeListDTO dto = new AreaTreeListDTO();
                    if (areaDTO.getLevel() == SysAreaLevel.ONE.getCode()) {
                        dto.setId(areaDTO.getId());
                        dto.setCode(areaDTO.getCountryCode());
                        dto.setName(areaDTO.getCountryTraditional());
                    } else if (areaDTO.getLevel() == SysAreaLevel.TWO.getCode()) {
                        dto.setId(areaDTO.getId());
                        dto.setCode(areaDTO.getProvinceCode());
                        dto.setName(areaDTO.getProvinceTraditional());
                    } else if (areaDTO.getLevel() == SysAreaLevel.THREE.getCode()) {
                        dto.setId(areaDTO.getId());
                        dto.setCode(areaDTO.getCityCode());
                        dto.setName(areaDTO.getCityTraditional());
                    } else if (areaDTO.getLevel() == SysAreaLevel.FOUR.getCode()) {
                        dto.setId(areaDTO.getId());
                        dto.setCode("-");
                        dto.setName(areaDTO.getAreaTraditional());
                    }
                    areaTreeList.add(dto);
                }

            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return areaTreeList;
    }

    @Override
    public List<AreaDTO> esOneLevel(String name) {
        List<AreaDTO> list = new ArrayList<>();
        SearchSourceBuilder ssb = new SearchSourceBuilder();
        BoolQueryBuilder bqb = QueryBuilders.boolQuery();
        if (StringUtils.isNotBlank(name)) {
            bqb.must(QueryBuilders.boolQuery()
                    .should(QueryBuilders.matchPhraseQuery("countrySimple", name))
                    .should(QueryBuilders.matchPhraseQuery("countryTraditional", name))
                    .should(QueryBuilders.matchPhraseQuery("countryPinyin", name))
                    .should(QueryBuilders.matchPhraseQuery("countryCode", name))
            );
        }
        bqb.must(QueryBuilders.termQuery("level", SysAreaLevel.ONE.getCode()));
        ssb.query(bqb);
        SearchRequest sr = new SearchRequest(ElasticSearchConstant.SYSTEM_AREA).source(ssb);
        try {
            SearchResponse search = restHighLevelClient.search(sr, ElasticSearchConfiguration.COMMON_OPTIONS);
            // 检索到的命中记录
            SearchHits hits = search.getHits();
            // 提取检索到的记录
            SearchHit[] searchHits = hits.getHits();
            if (searchHits != null && searchHits.length > 0) {
                for (SearchHit sh : searchHits) {
                    String source = sh.getSourceAsString();
                    // 将命中记录反序列化成目的地对象
                    AreaDTO area = JSON.parseObject(source, AreaDTO.class);
                    list.add(area);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return list;
    }

    @Override
    public PageResponse<AreaDTO> queryList(AreaQueryReq areaQueryReq) {
        IPage<SysArea> page = new Page<>(areaQueryReq.getPageNo(), areaQueryReq.getPageSize());
        QueryWrapper<SysArea> queryWrapper = new QueryWrapper<SysArea>();
        String name = areaQueryReq.getName();
        boolean notBlank = StringUtils.isNotBlank(name);
        queryWrapper.lambda().eq(SysArea::getIsDeleted, IsDeletedCode.NO.getCode())
                .eq(areaQueryReq.getStatus() != null, SysArea::getStatus, areaQueryReq.getStatus())
                .in(areaQueryReq.getLevels() != null, SysArea::getLevel, areaQueryReq.getLevels());
        if (notBlank) {
            queryWrapper.lambda().and(e ->
                    e.like(SysArea::getCountryCode, name)
                            .or().like(SysArea::getCountryPinyin, name)
                            .or().like(SysArea::getCountrySimple, name)
                            .or().like(SysArea::getCountryTraditional, name)
                            .or().like(SysArea::getProvincePinyin, name)
                            .or().like(SysArea::getProvinceSimple, name)
                            .or().like(SysArea::getProvinceTraditional, name)
                            .or().like(SysArea::getCityPinyin, name)
                            .or().like(SysArea::getCitySimple, name)
                            .or().like(SysArea::getCityTraditional, name)
                            .or().like(SysArea::getAreaPinyin, name)
                            .or().like(SysArea::getAreaSimple, name)
                            .or().like(SysArea::getAreaTraditional, name)
            );
        }
        queryWrapper.lambda().orderByAsc(SysArea::getLevel);
        IPage<SysArea> iPage = baseMapper.selectPage(page, queryWrapper);
        List<SysArea> sysAreaList = iPage.getRecords();
        if (CollectionUtils.isEmpty(sysAreaList)) {
            return new PageResponse<>(new ArrayList<>(), iPage.getCurrent() == 1, iPage.getTotal() <= (iPage.getCurrent() * iPage.getSize()), iPage.getTotal(), iPage.getCurrent(), iPage.getSize());
        }
        //如果不为空就置顶加去重
        if (areaQueryReq.getIds() != null && areaQueryReq.getIds().size() > 0) {
            Map<Long, SysArea> map = new HashMap<>();
            List<Long> list = new ArrayList<>();
            list.addAll(areaQueryReq.getIds());
            sysAreaList.forEach(e -> {
                map.put(e.getId(), e);
            });
            Set<Long> longs = map.keySet();
            List<Long> collect = list.stream().filter(e -> !longs.contains(e)).collect(Collectors.toList());
            if (collect != null && collect.size() > 0) {
                List<SysArea> sysAreas = baseMapper.selectList(Wrappers.<SysArea>lambdaQuery().in(SysArea::getId, collect));
                sysAreas.forEach(e -> map.put(e.getId(), e));
            }
            List<SysArea> result = new ArrayList<>();
            areaQueryReq.getIds().forEach(e -> {
                result.add(map.get(e));
                map.remove(e);
            });
            sysAreaList.clear();
            //填充置顶的结果不能为空
            result.forEach(e -> {
                if (e != null) {
                    sysAreaList.add(e);
                }
            });
            if (map.size() > 0) {
                Collection<SysArea> coll = map.values();
                List<SysArea> list2 = new ArrayList<>(coll);
                Collections.sort(list2);//排序对象根据层级升序
                sysAreaList.addAll(list2);
            }
        }
        List<AreaDTO> areaDTOList = EntityUtil.copyList(sysAreaList, AreaDTO.class);
        return new PageResponse<>(areaDTOList, iPage.getCurrent() == 1, iPage.getTotal() <= (iPage.getCurrent() * iPage.getSize()), iPage.getTotal(), iPage.getCurrent(), iPage.getSize());
    }

    @Override
    public Result add(AreaAddReq areaAddReq, Long userId) {
        QueryWrapper<SysArea> qw = new QueryWrapper<>();
        qw.lambda().select(SysArea::getId)
                .and(e ->
                        e.eq(SysArea::getCountryCode, areaAddReq.getCode())
                                .or().eq(SysArea::getProvinceCode, areaAddReq.getCode())
                                .or().eq(SysArea::getCityCode, areaAddReq.getCode())
                ).eq(SysArea::getIsDeleted, IsDeletedCode.NO.getCode());
        Integer integer = baseMapper.selectCount(qw);
        if (integer > 0) {
            return Result.failed(SystemError.SYSTEM_2108);
        }
        SysArea sysArea1 = null;
        //改造父级作为当前新增的数据
        if (0 != areaAddReq.getParentId()) {
            sysArea1 = baseMapper.selectById(areaAddReq.getParentId());
            if (sysArea1 == null) {
                return Result.failed(SystemError.SYSTEM_2109);
            }
            sysArea1.setId(null);
        }
        SysArea sysArea = sysArea1 == null ? new SysArea() : sysArea1;
        int level = areaAddReq.getLevel();
        if (level == SysAreaLevel.ONE.getCode()) {
            sysArea.setCountryCode(areaAddReq.getCode());
            sysArea.setCountryPinyin(areaAddReq.getPinyin());
            //如果是繁体就转换成简体否则反之
            if (ZhConverterUtil.isTraditional(areaAddReq.getName())) {
                sysArea.setCountrySimple(ZhConverterUtil.toSimple(areaAddReq.getName()));
                sysArea.setCountryTraditional(areaAddReq.getName());
            } else {
                sysArea.setCountrySimple(areaAddReq.getName());
                sysArea.setCountryTraditional(ZhConverterUtil.toTraditional(areaAddReq.getName()));
            }
            sysArea.setParentId(0L);
        }
        if (level == SysAreaLevel.TWO.getCode()) {
            sysArea.setParentId(areaAddReq.getParentId());
            sysArea.setProvinceCode(areaAddReq.getCode());
            sysArea.setProvincePinyin(areaAddReq.getPinyin());
            if (ZhConverterUtil.isTraditional(areaAddReq.getName())) {
                sysArea.setProvinceSimple(ZhConverterUtil.toSimple(areaAddReq.getName()));
                sysArea.setProvinceTraditional(areaAddReq.getName());
            } else {
                sysArea.setProvinceSimple(areaAddReq.getName());
                sysArea.setProvinceTraditional(ZhConverterUtil.toTraditional(areaAddReq.getName()));
            }
        }
        if (level == SysAreaLevel.THREE.getCode()) {
            sysArea.setParentId(areaAddReq.getParentId());
            sysArea.setCityCode(areaAddReq.getCode());
            sysArea.setCityPinyin(areaAddReq.getPinyin());
            if (ZhConverterUtil.isTraditional(areaAddReq.getName())) {
                sysArea.setCitySimple(ZhConverterUtil.toSimple(areaAddReq.getName()));
                sysArea.setCityTraditional(areaAddReq.getName());
            } else {
                sysArea.setCitySimple(areaAddReq.getName());
                sysArea.setCityTraditional(ZhConverterUtil.toTraditional(areaAddReq.getName()));
            }
        }
        if (level == SysAreaLevel.FOUR.getCode()) {
            sysArea.setParentId(areaAddReq.getParentId());
            if (ZhConverterUtil.isTraditional(areaAddReq.getName())) {
                sysArea.setAreaSimple(ZhConverterUtil.toSimple(areaAddReq.getName()));
                sysArea.setAreaTraditional(areaAddReq.getName());
            } else {
                sysArea.setAreaSimple(areaAddReq.getName());
                sysArea.setAreaTraditional(ZhConverterUtil.toTraditional(areaAddReq.getName()));
            }
            sysArea.setAreaPinyin(areaAddReq.getPinyin());
        }
//        setParent(areaAddReq, sysArea);//填充上级(废弃)
        sysArea.setStatus(areaAddReq.getStatus());
        sysArea.setLevel(level);
        sysArea.setIsDeleted(IsDeletedCode.NO.getCode());
        sysArea.setCreateId(userId);
        sysArea.setModifiedId(userId);
        sysArea.setGmtCreate(LocalDateTime.now());
        sysArea.setGmtModified(LocalDateTime.now());
        int insert = baseMapper.insert(sysArea);
        if (insert > 0){
            return Result.success();
        }
        return Result.failed(SystemError.SYSTEM_2110);
    }

    private void setParent(AreaAddReq areaAddReq, SysArea sysArea) {
        SysArea parent = baseMapper.selectById(areaAddReq.getParentId());
        if (areaAddReq.getLevel() == SysAreaLevel.FOUR.getCode()) {
            if (parent != null) {
                sysArea.setCityCode(parent.getCityCode());
                sysArea.setCityEn(parent.getCityEn());
                sysArea.setCityPinyin(parent.getCityPinyin());
                sysArea.setCitySimple(parent.getCitySimple());
                sysArea.setCityTraditional(parent.getCityTraditional());
                //填充
                SysArea parent1 = baseMapper.selectById(parent.getParentId());
                if (parent1 != null) {
                    sysArea.setProvinceCode(parent1.getProvinceCode());
                    sysArea.setProvinceEn(parent1.getProvinceEn());
                    sysArea.setProvincePinyin(parent1.getProvincePinyin());
                    sysArea.setProvinceSimple(parent1.getProvinceSimple());
                    sysArea.setProvinceTraditional(parent1.getProvinceTraditional());
                    //填充
                    SysArea parent2 = baseMapper.selectById(parent1.getParentId());
                    if (parent2 != null) {
                        sysArea.setCountryCode(parent2.getCountryCode());
                        sysArea.setCountryEn(parent2.getCountryEn());
                        sysArea.setCountryId(parent2.getCountryId());
                        sysArea.setCountryPinyin(parent2.getCountryPinyin());
                        sysArea.setCountrySimple(parent2.getCountrySimple());
                        sysArea.setCountryTraditional(parent2.getCountryTraditional());
                    }
                }
            }
        }
        if (areaAddReq.getLevel() == SysAreaLevel.THREE.getCode()) {
            if (parent != null) {
                sysArea.setProvinceCode(parent.getProvinceCode());
                sysArea.setProvinceEn(parent.getProvinceEn());
                sysArea.setProvincePinyin(parent.getProvincePinyin());
                sysArea.setProvinceSimple(parent.getProvinceSimple());
                sysArea.setProvinceTraditional(parent.getProvinceTraditional());
                SysArea parent1 = baseMapper.selectById(parent.getParentId());
                if (parent1 != null) {
                    sysArea.setCountryCode(parent1.getCountryCode());
                    sysArea.setCountryEn(parent1.getCountryEn());
                    sysArea.setCountryId(parent1.getCountryId());
                    sysArea.setCountryPinyin(parent1.getCountryPinyin());
                    sysArea.setCountrySimple(parent1.getCountrySimple());
                    sysArea.setCountryTraditional(parent1.getCountryTraditional());
                }
            }
        }
        if (areaAddReq.getLevel() == SysAreaLevel.TWO.getCode()) {
            if (parent != null) {
                sysArea.setCountryCode(parent.getCountryCode());
                sysArea.setCountryEn(parent.getCountryEn());
                sysArea.setCountryId(parent.getCountryId());
                sysArea.setCountryPinyin(parent.getCountryPinyin());
                sysArea.setCountrySimple(parent.getCountrySimple());
                sysArea.setCountryTraditional(parent.getCountryTraditional());
            }
        }
    }

    @Override
    public void update(AreaAddReq areaAddReq, Long userId) {
        SysArea sysArea = baseMapper.selectById(areaAddReq.getId());
        if(sysArea!=null){
            Integer level = areaAddReq.getLevel();
            if (level == SysAreaLevel.ONE.getCode()) {
                sysArea.setCountryCode(areaAddReq.getCode());
                sysArea.setCountryPinyin(areaAddReq.getPinyin());
                if (ZhConverterUtil.isTraditional(areaAddReq.getName())) {
                    sysArea.setCountrySimple(ZhConverterUtil.toSimple(areaAddReq.getName()));
                    sysArea.setCountryTraditional(areaAddReq.getName());
                } else {
                    sysArea.setCountrySimple(areaAddReq.getName());
                    sysArea.setCountryTraditional(ZhConverterUtil.toTraditional(areaAddReq.getName()));
                }
                sysArea.setParentId(0L);
            }
            if (level == SysAreaLevel.TWO.getCode()) {
                sysArea.setParentId(areaAddReq.getParentId());
                sysArea.setProvinceCode(areaAddReq.getCode());
                if (ZhConverterUtil.isTraditional(areaAddReq.getName())) {
                    sysArea.setProvinceSimple(ZhConverterUtil.toSimple(areaAddReq.getName()));
                    sysArea.setProvincePinyin(areaAddReq.getName());
                } else {
                    sysArea.setProvinceSimple(areaAddReq.getName());
                    sysArea.setProvincePinyin(ZhConverterUtil.toTraditional(areaAddReq.getName()));
                }
            }
            if (level == SysAreaLevel.THREE.getCode()) {
                sysArea.setParentId(areaAddReq.getParentId());
                sysArea.setCityCode(areaAddReq.getCode());
                sysArea.setCityPinyin(areaAddReq.getPinyin());
                if (ZhConverterUtil.isTraditional(areaAddReq.getName())) {
                    sysArea.setCitySimple(ZhConverterUtil.toSimple(areaAddReq.getName()));
                    sysArea.setCityTraditional(areaAddReq.getName());
                } else {
                    sysArea.setCitySimple(areaAddReq.getName());
                    sysArea.setCityTraditional(ZhConverterUtil.toTraditional(areaAddReq.getName()));
                }
            }
            if (level == SysAreaLevel.FOUR.getCode()) {
                sysArea.setParentId(areaAddReq.getParentId());
                if (ZhConverterUtil.isTraditional(areaAddReq.getName())) {
                    sysArea.setAreaSimple(ZhConverterUtil.toSimple(areaAddReq.getName()));
                    sysArea.setAreaTraditional(areaAddReq.getName());
                } else {
                    sysArea.setAreaSimple(areaAddReq.getName());
                    sysArea.setAreaTraditional(ZhConverterUtil.toTraditional(areaAddReq.getName()));
                }
                sysArea.setAreaPinyin(areaAddReq.getPinyin());
            }
            sysArea.setStatus(areaAddReq.getStatus());
            sysArea.setModifiedId(userId);
            sysArea.setGmtModified(LocalDateTime.now());
            baseMapper.updateById(sysArea);
        }
    }

    @Override
    public void delete(AreaIdReq areaIdReq, Long userId) {
        SysArea sysArea = new SysArea();
        sysArea.setGmtModified(LocalDateTime.now());
        sysArea.setModifiedId(userId);
        sysArea.setIsDeleted(IsDeletedCode.YES.getCode());
        sysArea.setId(areaIdReq.getId());
        baseMapper.updateById(sysArea);
    }

    @Override
    public void test() {
        List<SysArea> sysAreaList = baseMapper.selectList(null);
        HashMap<String, SysAreaTest> hashMap = new HashMap();
        List<SysAreaTest> list = new ArrayList<>();
        for (SysArea sysArea : sysAreaList) {
            String country = sysArea.getCountryCode();
            String province = sysArea.getProvinceCode();
            String city = sysArea.getCityCode();
            if (hashMap.get(country) != null) {
                if (hashMap.get(province) != null) {
                    if (hashMap.get(city) == null) {
                        SysAreaTest sysAreaTest3 = new SysAreaTest();
                        sysAreaTest3.setCityCode(sysArea.getCityCode());
                        sysAreaTest3.setCityEn(sysArea.getCityEn());
                        sysAreaTest3.setCityPinyin(sysArea.getCityPinyin());
                        sysAreaTest3.setCitySimple(sysArea.getCitySimple());
                        sysAreaTest3.setCityTraditional(sysArea.getCityTraditional());
                        sysAreaTest3.setParentId(hashMap.get(province).getId());
                        sysAreaTest3.setLevel(SysAreaLevel.THREE.getCode());
                        list.add(sysAreaTest3);
                        hashMap.put(sysArea.getCityCode(), sysAreaTest3);
                    }
                } else {
                    Long provinceId = IdWorker.getId();
                    SysAreaTest sysAreaTest2 = new SysAreaTest();
                    sysAreaTest2.setProvinceCode(sysArea.getProvinceCode());
                    sysAreaTest2.setProvinceEn(sysArea.getProvinceEn());
                    sysAreaTest2.setProvincePinyin(sysArea.getProvincePinyin());
                    sysAreaTest2.setProvinceSimple(sysArea.getProvinceSimple());
                    sysAreaTest2.setProvinceTraditional(sysArea.getProvinceTraditional());
                    sysAreaTest2.setParentId(hashMap.get(country).getId());
                    sysAreaTest2.setId(provinceId);
                    sysAreaTest2.setLevel(SysAreaLevel.TWO.getCode());
                    list.add(sysAreaTest2);
                    hashMap.put(sysArea.getProvinceCode(), sysAreaTest2);
                    SysAreaTest sysAreaTest3 = new SysAreaTest();
                    sysAreaTest3.setCityCode(sysArea.getCityCode());
                    sysAreaTest3.setCityEn(sysArea.getCityEn());
                    sysAreaTest3.setCityPinyin(sysArea.getCityPinyin());
                    sysAreaTest3.setCitySimple(sysArea.getCitySimple());
                    sysAreaTest3.setCityTraditional(sysArea.getCityTraditional());
                    sysAreaTest3.setParentId(provinceId);
                    sysAreaTest3.setLevel(SysAreaLevel.THREE.getCode());
                    list.add(sysAreaTest3);
                    hashMap.put(sysArea.getCityCode(), sysAreaTest3);
                }
            } else {
                Long countryId = IdWorker.getId();
                SysAreaTest sysAreaTest1 = new SysAreaTest();
                sysAreaTest1.setCountryCode(sysArea.getCountryCode());
                sysAreaTest1.setCountryEn(sysArea.getCountryEn());
                sysAreaTest1.setCountryPinyin(sysArea.getCountryPinyin());
                sysAreaTest1.setCountrySimple(sysArea.getCountrySimple());
                sysAreaTest1.setCountryTraditional(sysArea.getCountryTraditional());
                sysAreaTest1.setLevel(SysAreaLevel.ONE.getCode());
                sysAreaTest1.setId(countryId);
                sysAreaTest1.setParentId(0L);
                list.add(sysAreaTest1);
                hashMap.put(sysArea.getCountryCode(), sysAreaTest1);
                Long provinceId = IdWorker.getId();
                SysAreaTest sysAreaTest2 = new SysAreaTest();
                sysAreaTest2.setProvinceCode(sysArea.getProvinceCode());
                sysAreaTest2.setProvinceEn(sysArea.getProvinceEn());
                sysAreaTest2.setProvincePinyin(sysArea.getProvincePinyin());
                sysAreaTest2.setProvinceSimple(sysArea.getProvinceSimple());
                sysAreaTest2.setProvinceTraditional(sysArea.getProvinceTraditional());
                sysAreaTest2.setParentId(countryId);
                sysAreaTest2.setId(provinceId);
                sysAreaTest2.setLevel(SysAreaLevel.TWO.getCode());
                list.add(sysAreaTest2);
                hashMap.put(sysArea.getProvinceCode(), sysAreaTest2);
                SysAreaTest sysAreaTest3 = new SysAreaTest();
                sysAreaTest3.setCityCode(sysArea.getCityCode());
                sysAreaTest3.setCityEn(sysArea.getCityEn());
                sysAreaTest3.setCityPinyin(sysArea.getCityPinyin());
                sysAreaTest3.setCitySimple(sysArea.getCitySimple());
                sysAreaTest3.setCityTraditional(sysArea.getCityTraditional());
                sysAreaTest3.setParentId(provinceId);
                sysAreaTest3.setLevel(SysAreaLevel.THREE.getCode());
                list.add(sysAreaTest3);
                hashMap.put(sysArea.getCityCode(), sysAreaTest3);
            }
        }
        sysAreaTestService.saveBatch(list);
    }

    @Override
    public List<AreaTreeDTO> queryAreaTree() {
        List<SysArea> sysAreaList = baseMapper.selectList(new QueryWrapper<SysArea>().lambda().eq(SysArea::getIsDeleted, 0));
        TreeNodeConfig treeNodeConfig = new TreeNodeConfig();
        // 自定义属性名
        // 默认支持排序
        treeNodeConfig.setWeightKey("sort");
        treeNodeConfig.setChildrenKey("children");
        //可配置树深度
        treeNodeConfig.setDeep(4);
        treeNodeConfig.setIdKey("id");
        //转换器
        List<Tree<String>> build = TreeUtil.build(sysAreaList, "0", treeNodeConfig,
                (treeNode, tree) -> {
                    tree.setId(treeNode.getId().toString());
                    tree.setParentId(treeNode.getParentId().toString());
                    Integer level = treeNode.getLevel();
                    if (level == SysAreaLevel.ONE.getCode()) {
                        tree.setName(treeNode.getCountryTraditional());
                        tree.putExtra("code", treeNode.getCountryCode());
                        tree.putExtra("pinyin", treeNode.getCountryPinyin());
                    }
                    if (level == SysAreaLevel.TWO.getCode()) {
                        tree.setName(treeNode.getProvinceTraditional());
                        tree.putExtra("code", treeNode.getProvinceCode());
                        tree.putExtra("pinyin", treeNode.getProvincePinyin());
                    }
                    if (level == SysAreaLevel.THREE.getCode()) {
                        tree.setName(treeNode.getCityTraditional());
                        tree.putExtra("code", treeNode.getCityCode());
                        tree.putExtra("pinyin", treeNode.getCityPinyin());
                    }
                    if (level == SysAreaLevel.FOUR.getCode()) {
                        tree.setName(treeNode.getAreaTraditional());
                        tree.putExtra("code", "-");//表没有设计县级码
                        tree.putExtra("pinyin", treeNode.getAreaPinyin());
                    }
                    tree.putExtra("status", treeNode.getStatus());
                });
        return JSONArray.parseArray(JSONObject.toJSONString(build), AreaTreeDTO.class);
    }

    @Override
    public List<AreaTreeListDTO> queryAreaLikeName(String name) {
        QueryWrapper<SysArea> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().and(e -> e.like(SysArea::getCountryTraditional, name)
                .or().like(SysArea::getProvinceTraditional, name)
                .or().like(SysArea::getCityTraditional, name)
                .or().like(SysArea::getCountrySimple, name)
                .or().like(SysArea::getProvinceSimple, name)
                .or().like(SysArea::getCitySimple, name)
                .or().like(SysArea::getCountryCode, name)
                .or().like(SysArea::getProvinceCode, name)
                .or().like(SysArea::getCityCode, name)
                .or().like(SysArea::getCountryEn, name)
                .or().like(SysArea::getProvinceEn, name)
                .or().like(SysArea::getCityEn, name)
                .or().like(SysArea::getCountryPinyin, name)
                .or().like(SysArea::getProvincePinyin, name)
                .or().like(SysArea::getCityPinyin, name));
        queryWrapper.lambda().eq(SysArea::getIsDeleted, IsDeletedCode.NO.getCode())
                .in(SysArea::getLevel, SysAreaLevel.ONE.getCode(), SysAreaLevel.TWO.getCode(), SysAreaLevel.THREE.getCode());
//        List<SysArea> sysAreaList = baseMapper.selectList(queryWrapper);
        Page<SysArea> page = new Page<>(1, 10);
        Page<SysArea> areaPage = baseMapper.selectPage(page, queryWrapper);
        List<SysArea> sysAreaList = areaPage.getRecords();

        List<AreaTreeListDTO> areaTreeListDTOS = new ArrayList<>();
        for (SysArea sysArea : sysAreaList) {
            if (sysArea.getLevel() == SysAreaLevel.ONE.getCode()) {
                AreaTreeListDTO treeListDTO = new AreaTreeListDTO();
                treeListDTO.setId(sysArea.getId());
                treeListDTO.setCode(sysArea.getCountryCode());
                treeListDTO.setName(sysArea.getCountryTraditional());
                areaTreeListDTOS.add(treeListDTO);
            } else if (sysArea.getLevel() == SysAreaLevel.TWO.getCode()) {
                AreaTreeListDTO treeListDTO = new AreaTreeListDTO();
                treeListDTO.setId(sysArea.getId());
                treeListDTO.setCode(sysArea.getProvinceCode());
                treeListDTO.setName(sysArea.getProvinceTraditional());
                SysArea one = baseMapper.selectOne(new QueryWrapper<SysArea>().lambda().eq(SysArea::getId, sysArea.getParentId()).eq(SysArea::getStatus, IsDeletedCode.NO.getCode()));
                treeListDTO.setParentId(sysArea.getParentId());
                treeListDTO.setParentCode(one != null ? one.getCountryCode() : null);
                treeListDTO.setParentName(one != null ? one.getCountryTraditional() : null);
                areaTreeListDTOS.add(treeListDTO);
            } else if (sysArea.getLevel() == SysAreaLevel.THREE.getCode()) {
                AreaTreeListDTO treeListDTO = new AreaTreeListDTO();
                treeListDTO.setId(sysArea.getId());
                treeListDTO.setCode(sysArea.getCityCode());
                treeListDTO.setName(sysArea.getCityTraditional());
                SysArea one = baseMapper.selectOne(new QueryWrapper<SysArea>().lambda().eq(SysArea::getId, sysArea.getParentId()).eq(SysArea::getStatus, IsDeletedCode.NO.getCode()));
                treeListDTO.setParentId(sysArea.getParentId());
                treeListDTO.setParentCode(one != null ? one.getProvinceCode() : null);
                treeListDTO.setParentName(one != null ? one.getProvinceTraditional() : null);
                areaTreeListDTOS.add(treeListDTO);
            } else if (sysArea.getLevel() == SysAreaLevel.FOUR.getCode()) {
                AreaTreeListDTO treeListDTO = new AreaTreeListDTO();
                treeListDTO.setId(sysArea.getId());
                treeListDTO.setCode("-");//没有
                treeListDTO.setName(sysArea.getAreaTraditional());
                SysArea one = baseMapper.selectOne(new QueryWrapper<SysArea>().lambda().eq(SysArea::getId, sysArea.getParentId()).eq(SysArea::getStatus, IsDeletedCode.NO.getCode()));
                treeListDTO.setParentId(sysArea.getParentId());
                treeListDTO.setParentCode(one != null ? one.getCityCode() : null);
                treeListDTO.setParentName(one != null ? one.getCityTraditional() : null);
                areaTreeListDTOS.add(treeListDTO);
            }
        }
        return areaTreeListDTOS;
    }

    @Override
    public PageResponse<AreaTreeListDTO> queryAreaLikeNamePost(AreaQueryLikeNameReq req) {
        QueryWrapper<SysArea> queryWrapper = new QueryWrapper<>();
        Page<SysArea> page = new Page<>(req.getPageNo(), req.getPageSize());
        if (StringUtils.isNotBlank(req.getName())) {
            queryWrapper.lambda().and(e -> e.like(SysArea::getCountryTraditional, req.getName())
                    .or().like(SysArea::getProvinceTraditional, req.getName())
                    .or().like(SysArea::getCityTraditional, req.getName())
                    .or().like(SysArea::getCountrySimple, req.getName())
                    .or().like(SysArea::getProvinceSimple, req.getName())
                    .or().like(SysArea::getCitySimple, req.getName())
                    .or().like(SysArea::getCountryCode, req.getName())
                    .or().like(SysArea::getProvinceCode, req.getName())
                    .or().like(SysArea::getCityCode, req.getName())
                    .or().like(SysArea::getCountryEn, req.getName())
                    .or().like(SysArea::getProvinceEn, req.getName())
                    .or().like(SysArea::getCityEn, req.getName())
                    .or().like(SysArea::getCountryPinyin, req.getName())
                    .or().like(SysArea::getProvincePinyin, req.getName())
                    .or().like(SysArea::getCityPinyin, req.getName()));
        }
        queryWrapper.lambda().eq(SysArea::getIsDeleted, IsDeletedCode.NO.getCode());
        queryWrapper.lambda().eq(null != req.getStatus(), SysArea::getStatus, req.getStatus());
        Page<SysArea> iPage = baseMapper.selectPage(page, queryWrapper);
        List<SysArea> sysAreaList = iPage.getRecords();
        List<AreaTreeListDTO> areaTreeListDTOS = new ArrayList<>();
        for (SysArea sysArea : sysAreaList) {
            if (sysArea.getLevel() == SysAreaLevel.ONE.getCode()) {
                AreaTreeListDTO treeListDTO = new AreaTreeListDTO();
                treeListDTO.setId(sysArea.getId());
                treeListDTO.setCode(sysArea.getCountryCode());
                treeListDTO.setName(sysArea.getCountryTraditional());
                treeListDTO.setParentName("");
                treeListDTO.setParentCode("");
                treeListDTO.setParentId(0L);
                areaTreeListDTOS.add(treeListDTO);
            } else if (sysArea.getLevel() == SysAreaLevel.TWO.getCode()) {
                AreaTreeListDTO treeListDTO = new AreaTreeListDTO();
                treeListDTO.setId(sysArea.getId());
                treeListDTO.setCode(sysArea.getProvinceCode());
                treeListDTO.setName(sysArea.getProvinceTraditional());
                SysArea one = baseMapper.selectOne(new QueryWrapper<SysArea>().lambda().eq(SysArea::getId, sysArea.getParentId()).eq(SysArea::getStatus, IsDeletedCode.NO.getCode()));
                treeListDTO.setParentId(sysArea.getParentId());
                treeListDTO.setParentCode(one.getCountryCode());
                treeListDTO.setParentName(one.getCountryTraditional());
                areaTreeListDTOS.add(treeListDTO);
            } else if (sysArea.getLevel() == SysAreaLevel.THREE.getCode()) {
                AreaTreeListDTO treeListDTO = new AreaTreeListDTO();
                treeListDTO.setId(sysArea.getId());
                treeListDTO.setCode(sysArea.getCityCode());
                treeListDTO.setName(sysArea.getCityTraditional());
                SysArea one = baseMapper.selectOne(new QueryWrapper<SysArea>().lambda().eq(SysArea::getId, sysArea.getParentId()).eq(SysArea::getStatus, IsDeletedCode.NO.getCode()));
                treeListDTO.setParentId(sysArea.getParentId());
                treeListDTO.setParentCode(one.getProvinceCode());
                treeListDTO.setParentName(one.getProvinceTraditional());
                areaTreeListDTOS.add(treeListDTO);
            } else if (sysArea.getLevel() == SysAreaLevel.FOUR.getCode()) {
                AreaTreeListDTO treeListDTO = new AreaTreeListDTO();
                treeListDTO.setId(sysArea.getId());
                treeListDTO.setCode("-");//没有
                treeListDTO.setName(sysArea.getAreaTraditional());
                SysArea one = baseMapper.selectOne(new QueryWrapper<SysArea>().lambda().eq(SysArea::getId, sysArea.getParentId()).eq(SysArea::getStatus, IsDeletedCode.NO.getCode()));
                treeListDTO.setParentId(sysArea.getParentId());
                treeListDTO.setParentCode(one.getCityCode());
                treeListDTO.setParentName(one.getCityTraditional());
                areaTreeListDTOS.add(treeListDTO);
            }
        }
        if (CollectionUtils.isEmpty(areaTreeListDTOS)) {
            return new PageResponse<>(new ArrayList<>(), iPage.getCurrent() == 1, iPage.getTotal() <= (iPage.getCurrent() * iPage.getSize()), iPage.getTotal(), iPage.getCurrent(), iPage.getSize());
        }
        return new PageResponse<>(areaTreeListDTOS, iPage.getCurrent() == 1, iPage.getTotal() <= (iPage.getCurrent() * iPage.getSize()), iPage.getTotal(), iPage.getCurrent(), iPage.getSize());
    }

    @Override
    public AreaTreeListDTO queryById(AreaQueryIdReq req) {
        QueryWrapper<SysArea> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(SysArea::getId, req.getId());
        queryWrapper.lambda().eq(null != req.getStatus(), SysArea::getStatus, req.getStatus());
        queryWrapper.lambda().eq(SysArea::getIsDeleted, IsDeletedCode.NO.getCode());
        SysArea sysArea = baseMapper.selectOne(queryWrapper);
        AreaTreeListDTO areaTreeListDTO = new AreaTreeListDTO();
        if (sysArea != null) {
            if (sysArea.getLevel() == SysAreaLevel.ONE.getCode()) {
                areaTreeListDTO.setId(sysArea.getId());
                areaTreeListDTO.setCode(sysArea.getCountryCode());
                areaTreeListDTO.setName(sysArea.getCountryTraditional());
            } else if (sysArea.getLevel() == SysAreaLevel.TWO.getCode()) {
                areaTreeListDTO.setId(sysArea.getId());
                areaTreeListDTO.setCode(sysArea.getProvinceCode());
                areaTreeListDTO.setName(sysArea.getProvinceTraditional());
            } else if (sysArea.getLevel() == SysAreaLevel.THREE.getCode()) {
                areaTreeListDTO.setId(sysArea.getId());
                areaTreeListDTO.setCode(sysArea.getCityCode());
                areaTreeListDTO.setName(sysArea.getCityTraditional());
            } else if (sysArea.getLevel() == SysAreaLevel.FOUR.getCode()) {
                areaTreeListDTO.setId(sysArea.getId());
                areaTreeListDTO.setCode("-");
                areaTreeListDTO.setName(sysArea.getAreaTraditional());
            }
        }
        return areaTreeListDTO;
    }

    @Override
    public List<AreaTreeListDTO> queryByIds(List<Long> ids) {
        QueryWrapper<SysArea> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().in(SysArea::getId, ids);
        queryWrapper.lambda().eq(SysArea::getStatus, 0);
        queryWrapper.lambda().eq(SysArea::getIsDeleted, IsDeletedCode.NO.getCode());
        List<SysArea> sysAreaList = baseMapper.selectList(queryWrapper);
        List<AreaTreeListDTO> areaTreeListDTOList = new ArrayList<>();
        for (SysArea sysArea : sysAreaList) {
            AreaTreeListDTO areaTreeListDTO = new AreaTreeListDTO();
            if (sysArea != null) {
                if (sysArea.getLevel() == SysAreaLevel.ONE.getCode()) {
                    areaTreeListDTO.setId(sysArea.getId());
                    areaTreeListDTO.setCode(sysArea.getCountryCode());
                    areaTreeListDTO.setName(sysArea.getCountryTraditional());
                } else if (sysArea.getLevel() == SysAreaLevel.TWO.getCode()) {
                    areaTreeListDTO.setId(sysArea.getId());
                    areaTreeListDTO.setCode(sysArea.getProvinceCode());
                    areaTreeListDTO.setName(sysArea.getProvinceTraditional());
                } else if (sysArea.getLevel() == SysAreaLevel.THREE.getCode()) {
                    areaTreeListDTO.setId(sysArea.getId());
                    areaTreeListDTO.setCode(sysArea.getCityCode());
                    areaTreeListDTO.setName(sysArea.getCityTraditional());
                } else if (sysArea.getLevel() == SysAreaLevel.FOUR.getCode()) {
                    areaTreeListDTO.setId(sysArea.getId());
                    areaTreeListDTO.setCode("-");
                    areaTreeListDTO.setName(sysArea.getAreaTraditional());
                }
            }
        }

        return areaTreeListDTOList;
    }

    @Override
    public AreaHasChildrenDTO queryArea(AreaIdReq req) {
        SysArea sysArea = baseMapper.selectById(req.getId());
        AreaHasChildrenDTO areaHasChildrenDTO = new AreaHasChildrenDTO();
        QueryWrapper<SysArea> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(SysArea::getIsDeleted, IsDeletedCode.NO.getCode());
        queryWrapper.lambda().eq(SysArea::getParentId, sysArea.getId());
        queryWrapper.lambda().orderByAsc(SysArea::getCountryCode, SysArea::getProvinceCode, SysArea::getCityCode);
        Integer count = baseMapper.selectCount(queryWrapper);
        if (sysArea.getLevel() == SysAreaLevel.ONE.getCode()) {
            areaHasChildrenDTO.setCode(sysArea.getCountryCode());
            areaHasChildrenDTO.setId(sysArea.getId());
            areaHasChildrenDTO.setName(sysArea.getCountryTraditional());
            areaHasChildrenDTO.setStatus(sysArea.getStatus());
        } else if (sysArea.getLevel() == SysAreaLevel.TWO.getCode()) {
            areaHasChildrenDTO.setCode(sysArea.getProvinceCode());
            areaHasChildrenDTO.setId(sysArea.getId());
            areaHasChildrenDTO.setName(sysArea.getProvinceTraditional());
            areaHasChildrenDTO.setStatus(sysArea.getStatus());
        } else if (sysArea.getLevel() == SysAreaLevel.THREE.getCode()) {
            areaHasChildrenDTO.setCode(sysArea.getCityCode());
            areaHasChildrenDTO.setId(sysArea.getId());
            areaHasChildrenDTO.setName(sysArea.getCityTraditional());
            areaHasChildrenDTO.setStatus(sysArea.getStatus());
        } else if (sysArea.getLevel() == SysAreaLevel.FOUR.getCode()) {
            areaHasChildrenDTO.setCode("-");
            areaHasChildrenDTO.setId(sysArea.getId());
            areaHasChildrenDTO.setName(sysArea.getAreaTraditional());
            areaHasChildrenDTO.setStatus(sysArea.getStatus());
        }
        if (count != 0) {
            areaHasChildrenDTO.setHasChildren(true);
        } else {
            areaHasChildrenDTO.setHasChildren(false);
        }
        return areaHasChildrenDTO;
    }

    @Override
    public AreaChildrenDTO queryAreaChildren(AreaIdReq req) {
        AreaChildrenDTO areaChildrenDTO = new AreaChildrenDTO();
        SysArea sysArea = baseMapper.selectById(req.getId());
        QueryWrapper<SysArea> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(SysArea::getIsDeleted, IsDeletedCode.NO.getCode());
        queryWrapper.lambda().eq(SysArea::getParentId, sysArea.getId());
        queryWrapper.lambda().orderByAsc(SysArea::getCountryCode, SysArea::getProvinceCode, SysArea::getCityCode);
        List<SysArea> sysAreaList = baseMapper.selectList(queryWrapper);
        if (sysArea.getLevel() == SysAreaLevel.ONE.getCode()) {
            areaChildrenDTO.setCode(sysArea.getCountryCode());
            areaChildrenDTO.setId(sysArea.getId());
            areaChildrenDTO.setName(sysArea.getCountryTraditional());
            areaChildrenDTO.setStatus(sysArea.getStatus());
            areaChildrenDTO.setPinyin(sysArea.getCountryPinyin());
            areaChildrenDTO.setLevel(SysAreaLevel.ONE.getCode());
            List<AreaChildrenDTO> childrenDTOS = new ArrayList<>();
            for (SysArea area : sysAreaList) {
                AreaChildrenDTO dto = new AreaChildrenDTO();
                dto.setCode(area.getProvinceCode());
                dto.setId(area.getId());
                dto.setName(area.getProvinceTraditional());
                dto.setStatus(area.getStatus());
                dto.setPinyin(area.getProvincePinyin());
                dto.setLevel(SysAreaLevel.TWO.getCode());
                AreaIdReq idReq = new AreaIdReq();
                idReq.setId(area.getId());
                AreaHasChildrenDTO areaHasChildrenDTO = this.queryArea(idReq);
                dto.setHasChildren(areaHasChildrenDTO.getHasChildren());
                childrenDTOS.add(dto);
            }
            areaChildrenDTO.setChildren(childrenDTOS);
        } else if (sysArea.getLevel() == SysAreaLevel.TWO.getCode()) {
            areaChildrenDTO.setCode(sysArea.getProvinceCode());
            areaChildrenDTO.setId(sysArea.getId());
            areaChildrenDTO.setName(sysArea.getProvinceTraditional());
            areaChildrenDTO.setStatus(sysArea.getStatus());
            areaChildrenDTO.setPinyin(sysArea.getProvincePinyin());
            areaChildrenDTO.setLevel(SysAreaLevel.TWO.getCode());
            List<AreaChildrenDTO> childrenDTOS = new ArrayList<>();
            for (SysArea area : sysAreaList) {
                AreaChildrenDTO dto = new AreaChildrenDTO();
                dto.setCode(area.getCityCode());
                dto.setId(area.getId());
                dto.setName(area.getCityTraditional());
                dto.setStatus(area.getStatus());
                dto.setPinyin(area.getCityPinyin());
                dto.setLevel(SysAreaLevel.THREE.getCode());
                AreaIdReq idReq = new AreaIdReq();
                idReq.setId(area.getId());
                AreaHasChildrenDTO areaHasChildrenDTO = this.queryArea(idReq);
                dto.setHasChildren(areaHasChildrenDTO.getHasChildren());
                childrenDTOS.add(dto);
            }
            areaChildrenDTO.setChildren(childrenDTOS);
        } else if (sysArea.getLevel() == SysAreaLevel.THREE.getCode()) {
            areaChildrenDTO.setCode(sysArea.getCityCode());
            areaChildrenDTO.setId(sysArea.getId());
            areaChildrenDTO.setName(sysArea.getCityTraditional());
            areaChildrenDTO.setStatus(sysArea.getStatus());
            areaChildrenDTO.setPinyin(sysArea.getCityPinyin());
            areaChildrenDTO.setLevel(SysAreaLevel.THREE.getCode());
            List<AreaChildrenDTO> childrenDTOS = new ArrayList<>();
            for (SysArea area : sysAreaList) {
                AreaChildrenDTO dto = new AreaChildrenDTO();
                dto.setCode("-");
                dto.setId(area.getId());
                dto.setName(area.getAreaTraditional());
                dto.setStatus(area.getStatus());
                dto.setPinyin(area.getAreaPinyin());
                dto.setLevel(SysAreaLevel.FOUR.getCode());
                AreaIdReq idReq = new AreaIdReq();
                idReq.setId(area.getId());
                AreaHasChildrenDTO areaHasChildrenDTO = this.queryArea(idReq);
                dto.setHasChildren(areaHasChildrenDTO.getHasChildren());
                childrenDTOS.add(dto);
            }
            areaChildrenDTO.setChildren(childrenDTOS);
        } else if (sysArea.getLevel() == SysAreaLevel.FOUR.getCode()) {
            areaChildrenDTO.setCode("-");
            areaChildrenDTO.setId(sysArea.getId());
            areaChildrenDTO.setName(sysArea.getAreaTraditional());
            areaChildrenDTO.setStatus(sysArea.getStatus());
            areaChildrenDTO.setPinyin(sysArea.getAreaPinyin());
            areaChildrenDTO.setLevel(SysAreaLevel.FOUR.getCode());
        }
        return areaChildrenDTO;
    }

    @Override
    public List<AreaHasChildrenDTO> queryFirstArea() {
        List<AreaHasChildrenDTO> oneLevelArea = baseMapper.getOneLevelArea(IsDeletedCode.NO.getCode(), SysAreaLevel.ONE.getCode(), SysAreaLevel.TWO.getCode());
        return oneLevelArea;
    }

    @Override
    public AreaDTO query(AreaQueryReq areaQueryReq) {
        QueryWrapper<SysArea> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("status", 0)
                .eq("is_deleted", IsDeletedCode.NO.getCode())
                .eq("city_traditional", areaQueryReq.getName());
        List<SysArea> list = baseMapper.selectList(queryWrapper);
        AreaDTO areaDTO = new AreaDTO();
        if (CollectionUtils.isNotEmpty(list)) {
            SysArea sysArea = list.get(0);
            areaDTO.setId(sysArea.getId());
        }
        return areaDTO;
    }

    @Override
    public AreaDTO query(String name, int type) {
        QueryWrapper<SysArea> qw = new QueryWrapper<>();
        qw.lambda().eq(SysArea::getIsDeleted, IsDeletedCode.NO.getCode());
        if (type == 1) {
            qw.lambda().eq(SysArea::getAreaTraditional, name);
        } else if (type == 2) {
            qw.lambda().eq(SysArea::getCityTraditional, name);
        } else {
            qw.lambda().eq(SysArea::getProvinceTraditional, name);
        }
        List<SysArea> sysAreas = baseMapper.selectList(qw);
        if (sysAreas != null && sysAreas.size() > 0) {
            AreaDTO copy = EntityUtil.copy(sysAreas.get(0), AreaDTO.class);
            return copy;
        }
        return null;
    }

    public Result refreshTask() {
        return Result.success(putData());
    }

    @Override
    public void updateElasticSearch() {
        sysAreaElasticSearchMapper.deleteAll();
        //只缓存启用的和未删除的
        List<SysArea> sysAreas = baseMapper.selectList(
                Wrappers.<SysArea>lambdaQuery().eq(SysArea::getIsDeleted, IsDeletedCode.NO.getCode())
                        .eq(SysArea::getStatus, IsDeletedCode.NO.getCode())
        );
        List<SysAreaDTO> sysAreaDTOS = EntityUtil.copyList(sysAreas, SysAreaDTO.class);
        sysAreaElasticSearchMapper.saveAll(sysAreaDTOS);
    }

    private boolean deleteIndex() {
        try {
            sysAreaElasticSearchMapper.deleteAll();
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
        return true;
    }

    private boolean putData() {
        try {
            // 判断索引是否存在
            GetIndexRequest getIndexRequest = new GetIndexRequest(ElasticSearchConstant.SYSTEM_AREA);
            boolean exists = restHighLevelClient.indices().exists(getIndexRequest, RequestOptions.DEFAULT);
            if (!exists) {
                // 不存在则创建
                updateElasticSearch();
                lastModifiedTime = null;
            }

            if (lastModifiedTime == null) {
                // 全量更新操作 1.删除索引并重新添加数据
                if (deleteIndex()) {
                    updateElasticSearch();
                    // 查询所有的数据然后新增到参数中
                    List<SysArea> sysAreas = baseMapper.selectList(
                            Wrappers.<SysArea>lambdaQuery().eq(SysArea::getIsDeleted, IsDeletedCode.NO.getCode())
                                    .eq(SysArea::getStatus, IsDeletedCode.NO.getCode())
                    );
                    List<SysAreaDTO> sysAreaDTOS = EntityUtil.copyList(sysAreas, SysAreaDTO.class);

                    if (sysAreaDTOS != null && sysAreaDTOS.size() > 0) {
                        for (SysAreaDTO item : sysAreaDTOS) {
                            IndexRequest indexRequest = new IndexRequest(ElasticSearchConstant.SCENIC);
                            indexRequest.id(String.valueOf(item.getId()));
                            indexRequest.source(JSON.toJSONString(item), XContentType.JSON);
                            try {
                                restHighLevelClient.index(indexRequest, RequestOptions.DEFAULT);
                            } catch (Exception e) {
                                e.printStackTrace();
                            }
                        }
                        lastModifiedTime = LocalDateTime.now();
                    }
                }
            } else {
                // 增量更新操作 1. 查询时间之后的数据
                String formatTime = lastModifiedTime.format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
                List<SysArea> sysAreas = baseMapper.selectList(
                        Wrappers.<SysArea>lambdaQuery().eq(SysArea::getIsDeleted, IsDeletedCode.NO.getCode())
                                .eq(SysArea::getStatus, IsDeletedCode.NO.getCode())
                                .and(
                                        e -> e.ge(SysArea::getGmtCreate, formatTime)
                                                .or().ge(SysArea::getGmtModified, formatTime)
                                )

                );
                if (sysAreas != null && sysAreas.size() > 0) {
                    for (SysArea item : sysAreas) {
                        // 查询数据是否存在
                        GetRequest getRequest = new GetRequest(ElasticSearchConstant.SCENIC);
                        getRequest.id(String.valueOf(item.getId()));
                        boolean haveFlag = restHighLevelClient.exists(getRequest, RequestOptions.DEFAULT);
                        if (!haveFlag) {
                            // 创建
                            IndexRequest indexRequest = new IndexRequest(ElasticSearchConstant.SCENIC);
                            indexRequest.id(String.valueOf(item.getId()));
                            indexRequest.source(JSON.toJSONString(item), XContentType.JSON);
                            restHighLevelClient.index(indexRequest, RequestOptions.DEFAULT);
                        } else {
                            // 更新
                            UpdateRequest updateRequest = new UpdateRequest();
                            updateRequest.index(ElasticSearchConstant.SCENIC);
                            updateRequest.id(String.valueOf(item.getId()));
                            updateRequest.doc(JSON.toJSONString(item), XContentType.JSON);
                            restHighLevelClient.update(updateRequest, RequestOptions.DEFAULT);
                        }
                    }
                    //刷新跟新时间
                    lastModifiedTime = LocalDateTime.now();
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
        return true;
    }
}
